#include "LoopThreadPool.h"
#include "LoopThread.h"
LoopThreadPool::LoopThreadPool(EventLoop *baseLoop)
    : _thread_count(0),
      _next_idx(0),
      _baseLoop(baseLoop)
{
}

// 1. 设置线程数量
void LoopThreadPool::SetThreadCount(int count)
{
    _thread_count = count;
}

// 2. 创建所有的从属线程
void LoopThreadPool::Create()
{
    if (_thread_count > 0)
    {
        _threads.resize(_thread_count);
        _loops.resize(_thread_count);
        for (int i = 0; i < _thread_count; i++)
        {
            _threads[i] = new LoopThread;
            _loops[i] = _threads[i]->GetLoop();
        }
    }
}

// 3. 实现RR轮转，使负载均衡
EventLoop *LoopThreadPool::NextLoop()
{
    if (_thread_count == 0)
        return _baseLoop;
    _next_idx = (_next_idx + 1) % _thread_count;
    return _loops[_next_idx];
}